package com.deneme;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import functions.images.PuzzleDifficulty;

public class SavePuzzle extends HttpServlet {
    
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    	/* get the puzzle configuration (i.e. state of the puzzle */
    	String configRaw = req.getParameter("config");
    	int[] config;
    	/* convert the string representation to an integer array */
    	if(!configRaw.isEmpty()) {
    		String[] configStr = configRaw.split(":");
    		config = new int[configStr.length];
    		for (int i = 0; i < configStr.length; ++i) {
    			config[i] = Integer.parseInt(configStr[i]);
    		}
    	}
    	/* if there is no configuration, set it to null */
    	else {
    		config = null;
    	}

    	/* get other parameters for the puzzle */
    	BlobKey key = new BlobKey(req.getParameter("blobkey"));
    	
    	int dimension = Integer.parseInt(req.getParameter("dimension"));
    	
    	PuzzleDifficulty difficulty = PuzzleDifficulty.valueOf(req.getParameter("difficulty"));
    	
    	String puzzlekey = req.getParameter("puzzlekey");

    	/* create a new puzzle object */
    	SavedPuzzle puzzle;
   		puzzle = new SavedPuzzle();
    	puzzle.setConfig(config);
    	puzzle.setDifficulty(difficulty);
    	puzzle.setDimension(dimension);
    	puzzle.setImgKey(key);
    	puzzle.save();
    	
    	/* this parameter signifies whether the user has clicked save or not */
    	/* if they have just created the puzzle we save it, but not to the user's saved puzzles list */
    	boolean saveToUser = req.getParameter("savetouser").equals("true");
    	System.out.println("saveToUser: " + saveToUser + " from req: " + req.getParameter("savetouser"));
    	if (saveToUser) {
    		/* if the user has clicked save, add this puzzle key to their list of keys */
    		System.out.println("saving to user");
    		UserService userService = UserServiceFactory.getUserService();
    		User user = userService.getCurrentUser();
    		UserData userData = UserData.getDataForUser(user);
    		userData.addPuzzleKey(puzzle.getId());
    	}
		
    	/* forward to the puzzle page to display puzzle */
    	RequestDispatcher rd = req.getRequestDispatcher("/puzzle?puzzle-key=" + puzzle.getId());
    	rd.forward(req, res);
    }

}
